package com.java.jvm.bytecode;

import javassist.*;

import java.io.IOException;
import java.lang.reflect.Field;

public class JavassistCreateClassTests {
    public static void main(String[] args) throws CannotCompileException, IOException, IllegalAccessException, InstantiationException, NoSuchFieldException {
        //创建新的字节码类型
        CtClass ctClass =
                ClassPool.getDefault()
                        .makeClass("com.java.jvm.WelcomeJVM");
        //设置类的访问修饰符
        ctClass.setModifiers(Modifier.PUBLIC);

        //构建新的类的成员变量
        CtField ctFieldNew = new CtField(CtClass.intType,"age",ctClass);
        //设置类的访问修饰符为public
        ctFieldNew.setModifiers(Modifier.PUBLIC);
        //将属性添加到类中
        ctClass.addField(ctFieldNew);

        Class<?> aClass = ctClass.toClass();
        System.out.println(aClass.getName());
        Object o = aClass.newInstance();
        Field ageField = aClass.getDeclaredField("age");
        ageField.set(o, 10);
        Integer o1 = (Integer)ageField.get(o);
        System.out.println(o1);


        // ctClass.writeFile("01-java/target/classes/");
    }
}
